package com.android.jianboshi.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.android.baselibrary.interface_.CommCallBack;
import com.android.baselibrary.tool.CommToast;
import com.android.baselibrary.tool.Log;
import com.android.baselibrary.tool.SPUtil;
import com.android.baselibrary.util.Util;
import com.android.baselibrary.view.Comm_HeadView;
import com.android.baselibrary.view.RoundProgressBar;
import com.android.jianboshi.R;
import com.android.jianboshi.bean.DataInfo;
import com.android.jianboshi.constants.SPConstants;
import com.android.jianboshi.dialog.Boxing_SpeedResult_DialogFragment;
import com.android.jianboshi.dialog.DaoJiShi_DialogFragment;
import com.android.jianboshi.event.Event_Notification;
import com.android.jianboshi.manager.BoxingHelper;
import com.android.jianboshi.manager.BoxingManager;
import com.android.jianboshi.manager.MedioPlayerUtil;
import com.android.jianboshi.ui.view.Tips_View;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class Boxing_SpeedActivity extends BaseActivity {

    @BindView(R.id.comm_title)
    Comm_HeadView comm_title;
    @BindView(R.id.roundprogressbar)
    RoundProgressBar roundprogressbar;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_hits)
    TextView tv_hits;
    @BindView(R.id.tv_kcal)
    TextView tv_kcal;
    @BindView(R.id.tv_retry)
    TextView tv_retry;
    @BindView(R.id.tips_view)
    Tips_View tips_view;

    MedioPlayerUtil playerUtil;
    Handler handler = new Handler();
    int time = 10;   //当前倒计时
    int totalTime = 0;   //总时间

    BoxingManager boxingManager = new BoxingManager();
    boolean isBegin = false;  //开始计数

    @Override
    protected int getLayoutId() {
        return R.layout.activity_boxing_speed;
    }

    @Override
    protected void initView() {
        totalTime = getIntent().getIntExtra("time", 10);
        time = totalTime;

        comm_title.setTitle(getString(R.string.boxing_speed));
        DaoJiShi_DialogFragment.showDialog(this, null).setCallback(new CommCallBack() {
            @Override
            public void onResult(Object obj) {
                //倒计时结束
                Log.i("倒计时结束");

                playerUtil = new MedioPlayerUtil(mContext, null);
                playerUtil.setData("music/daojishi2.mp3", true);

                handler.postDelayed(runnable, 0);

                isBegin = true;
            }
        });

        roundprogressbar.setMax(time);

    }


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            roundprogressbar.setProgress(time);
            tv_time.setText(time + "s");
            time--;
            if (time == -1) {
                tv_retry.setVisibility(View.VISIBLE);
                playerUtil.stop();
                tv_time.setText(totalTime + "s");

                isBegin = false;

                CommToast.showToast(mContext, getString(R.string.speed_timeout));
            } else {
                handler.postDelayed(runnable, 1000);
            }
        }
    };

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
    }

    @OnClick({R.id.tv_show_record,R.id.tv_retry})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_show_record:
                int Boxing_Speed_Max_Hits = Integer.parseInt(SPUtil.getStringValue(mContext, SPConstants.Boxing_Speed_Max_Hits + "_"+ totalTime, "0"));
                double Boxing_Speed_Max_KCal = Double.parseDouble(SPUtil.getStringValue(mContext, SPConstants.Boxing_Speed_Max_KCal+ "_"+ totalTime, "0"));

                Map<String, Object> params = new HashMap<>();
                //击打次数
                params.put(Boxing_SpeedResult_DialogFragment.Param_Hits, Boxing_Speed_Max_Hits);
                //卡路里
                params.put(Boxing_SpeedResult_DialogFragment.Param_Kcal, Boxing_Speed_Max_KCal);
                Boxing_SpeedResult_DialogFragment.showDialog(this, params);
                break;
            case R.id.tv_retry:
                Intent intent = new Intent(mContext, Boxing_SpeedActivity.class);
                intent.putExtra("time", totalTime);
                startActivity(intent);
                finish();
                break;
        }
    }

    @Override
    protected boolean isRegistEventbus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event_Notification event) {
        if (isBegin) {
            Log.i("数据");
            boxingManager.parseScanResult(event.data);
            showResult();
        }
        tips_view.setData(event.data);
    }

    /**
     * 解析扫描结果
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void showResult() {
        int hits = boxingManager.airPressureList.size();
        tv_hits.setText(boxingManager.airPressureList.size() + "");

        //计算平均力量
        List<Double> powerList = new ArrayList<>();
        for (DataInfo air : boxingManager.airPressureList) {
            double power = BoxingHelper.getPower(air);
            powerList.add(power);
        }
        double powerAvg = 0;
        if (powerList.size() > 0) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                powerAvg = powerList.stream().mapToDouble(Double::valueOf).average().getAsDouble();
            }
        }
        //卡路里
        double kcal = BoxingHelper.getKCal1(mContext, totalTime - time, hits, powerAvg);
        tv_kcal.setText(Util.numDecimalFormat(kcal + "", 1) + "");


        int Boxing_Speed_Max_Hits = Integer.parseInt(SPUtil.getStringValue(mContext, SPConstants.Boxing_Speed_Max_Hits+ "_"+ totalTime, "0"));
        double Boxing_Speed_Max_KCal = Double.parseDouble(SPUtil.getStringValue(mContext, SPConstants.Boxing_Speed_Max_KCal+ "_"+ totalTime, "0"));
        if (hits > Boxing_Speed_Max_Hits) {
            SPUtil.putValue(mContext, SPConstants.Boxing_Speed_Max_Hits+ "_"+ totalTime, hits + "");
        }
        if (kcal > Boxing_Speed_Max_KCal) {
            SPUtil.putValue(mContext, SPConstants.Boxing_Speed_Max_KCal+ "_"+ totalTime, kcal + "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
        playerUtil.stop();
    }
}
